<?php


namespace app\Activity\controller;


use app\activity\model\Activity;
use app\activity\model\Activity as ActivityModel;
use app\activity\model\ActivityClassify;
use app\activity\model\ActivityItem;
use app\activity\model\ActivityItemsInActivity;
use app\activity\model\AtvCompany;
use app\AdminRest;
use app\card\model\UserInfo;
use app\activity\validate\ActivityValidate;


class AdminActivity extends AdminRest
{
    public function listAll()
    {

        $param = $this->_param;
        $page_config = array(
            'page'       => 1,
            'page_count' => 20
        );
        //设置页码
        if (isset($param['page']) && $param['page'] > 0) $page_config['page'] = $param['page'];
        //设置每页的数据
        if (isset($param['page_count']) && $param['page_count'] > 0) $page_config['page_count'] = $param['page_count'];
        if (isset($param['classify_id']) && $param['classify_id'] > 0) $filter['classify_id'] = $param['classify_id'];
        $filter = [
            ['uniacid', '=', $this->_uniacid],
        ];



        if (isset($this->_param['titleForSearch']) && $this->_param['titleForSearch']) {

            $filter[] = ['title', 'like', '%' . $this->_param['titleForSearch'] . '%'];
        }

        //未开始
        if(!empty($param['active_status'])&&$param['active_status']==1){

            $filter[] = ['start_time','>',time()];

        }
        //进行中
        if(!empty($param['active_status'])&&$param['active_status']==2){

            $filter[] = ['start_time','<',time()];

            $filter[] = ['end_time','>',time()];

        }
        //已经结束
        if(!empty($param['active_status'])&&$param['active_status']==3){

            $filter[] = ['end_time','<',time()];

        }

        $model = new ActivityModel();
        $page_config['total'] = $model->countByFilter($filter);
        $rsts = $model->where($filter)
            ->field(['id', 'title', 'cover', 'classify_id', 'to_uid', 'detail_images', 'start_time', 'end_time', 'sign_limit', 'status'])
            ->page($page_config['page'], $page_config['page_count'])->order('id', 'desc')->select()->toArray();

        $classify_ids = array_column($rsts, 'classify_id');

        $m_activity_classify = new ActivityClassify();
        $classify_tmp = $m_activity_classify->field('id, title')->where('id', 'in', $classify_ids)->select()->toArray();
        $classify = [];
        foreach ($classify_tmp as $item) {
            $classify[$item['id']] = $item['title'];
        }


        $user_ids = array_column($rsts, 'to_uid');
        $m_user_info = new UserInfo();
        $users_temp = $m_user_info->field('fans_id, name')->where('fans_id', 'in', $user_ids)->select()->toArray();
        $users = [];
        foreach ($users_temp as $item) {
            $users[$item['fans_id']] = $item['name'];
        }



        foreach ($rsts as $k => $v) {

            $rsts[$k]['classify_name'] = $classify[$v['classify_id']] ?? '';

            $rsts[$k]['user_name'] = $users[$v['to_uid']] ?? '';
            //未开始
            if($v['start_time']>time()){

                $rsts[$k]['active_status'] = 1;
            }
            //进行中
            if($v['start_time']<time()&&$v['end_time']>time()){

                $rsts[$k]['active_status'] = 2;
            }
            //已结束
            if($v['end_time']<time()){

                $rsts[$k]['active_status'] = 3;
            }
        }

        $page_config['total_page'] = (int)($page_config['total'] / $page_config['page_count']);
        if (($page_config['total'] % $page_config['page_count']) > 0) $page_config['total_page'] = $page_config['total_page'] + 1;
        //设置返回参数
        $result = $page_config;
        //返回数据
        $rsts = transImagesOne($rsts, ['cover']);
        $result['data'] = $rsts;
        return $this->success($result);


    }

    public function createOne()
    {
        $validate = new ActivityValidate();
        $check = $validate->scene('create')->check($this->_input);

        if ($check == false)
        {
            return $this->error($validate->getError());
        }

        $input = $this->_input;
        if(!empty($input['detail_images'])&&strlen($input['detail_images'])>500){
            return $this->error('添加的图片过多');
        }
        if (isset($input['start_time']) || isset($input['end_time']) || isset($input['sign_start_time'])|| isset($input['sign_end_time']))
        {
            if ($input['start_time']  >= $input['end_time'])
            {
                return $this->error('开始时间必须小于结束时间');
            }

            if ($input['sign_start_time']  >= $input['sign_end_time'])
            {
                return $this->error('报名开始时间必须小于报名结束时间！');
            }

            if ($input['sign_start_time']   >= $input['start_time'])
            {
                return $this->error('报名开始时间必须小于活动开始时间！');
            }

            if ($input['sign_end_time']   > $input['end_time'])
            {
                return $this->error('报名结束时间必须小于活动结束时间');
            }
        }
        $input['uniacid'] = $this->_uniacid;

        $input['content_text'] = !empty($input['content_text'])?$input['content_text']:'';

        $model = new ActivityModel();

        if(!empty($input['company_id'])){

            $company_id = $input['company_id'];

            unset($input['company_id']);

        }

        $activity_id = $model->createOne($input);

        if (!$activity_id)
        {
            return $this->error('fail');
        }
        //判断是否是全选公司
        if($input['is_public']==0&&!empty($company_id)){

            $atv_model  = new AtvCompany();

            $company_id = $atv_model->changeData($company_id);

            $this->companyAdd($company_id,$activity_id);
        }

        $arcitity_item_ids = explode(',', $this->_input['items'] ?? '');

        $items_model = new \app\activity\model\ActivityItem();

        $acticity_items_data = $items_model->getAllByIds($arcitity_item_ids);

        $time = time();

        $saveData = [];
        foreach ($acticity_items_data as $data) {
            $saveData[] = [
                'create_time' => $time,
                'update_time' => $time,
                'activity_id' => $activity_id,
                'uniacid' => $this->_uniacid,
                'title' => $data['title']
            ];
        }

        $activityItemsInActivityModel = new ActivityItemsInActivity();
        $activityItemsInActivityModel->saveAll($saveData);

        return $this->success($activity_id);
    }

    /**
     * @param $data
     * @param $goods_id
     * 添加company_goods
     */
    public function companyAdd($data,$atv_id){

        $atv_model  = new AtvCompany();

        $atv_model->companyGoodsDel(['uniacid'=>$this->_uniacid,'atv_id'=>$atv_id],$data);

        foreach ($data as $v){

            $com = $atv_model->companyGoodsFind(['atv_id'=>$atv_id,'company_id'=>$v,'uniacid'=>$this->_uniacid]);

            if(empty($com)){

                $res = $atv_model->companyGoodsAdd(['uniacid'=>$this->_uniacid,'atv_id'=>$atv_id,'company_id'=>$v]);
            }

        }

        return !empty($res)?$res:1;
    }


    public function updateOne()
    {
        $activity_id   = $this->_input['id'] ?? null;

        $m_activity = new ActivityModel();
        $activity = $m_activity->where(['id' => $activity_id])->find();
        if (!$activity)
        {
            return $this->error('activity not found');
        }

        $input = $this->_input;
        //判断图片连接长度 500个字节
        if(!empty($input['detail_images'])&&strlen($input['detail_images'])>500){
            return $this->error('添加的图片过多');
        }

        if($activity['sign_number']>$input['sign_limit']){

            return $this->error('已有'.$activity['sign_number'].'个人成功报名,编辑限制人数不得小于'.$activity['sign_number'].'人');
        }

        if (isset($input['start_time']) || isset($input['end_time']) || isset($input['sign_start_time'])|| isset($input['sign_end_time']))
        {
            if (($input['start_time'] ?? $activity['start_time'] ) >= $input['end_time'] ?? $activity['end_time'])
            {
                return $this->error('开始时间必须小于结束时间');
            }

            if (($input['sign_start_time'] ?? $activity['sign_start_time'] ) >= $input['sign_end_time'] ?? $activity['sign_end_time'])
            {
                return $this->error('报名开始时间必须小于报名结束时间');
            }

            if (($input['sign_start_time'] ?? $activity['sign_start_time'] ) >= $input['start_time'] ?? $activity['start_time'])
            {
                return $this->error('报名开始时间必须小于活动开始时间');
            }

            if (($input['sign_end_time'] ?? $activity['sign_end_time'] ) > $input['end_time'] ?? $activity['end_time'])
            {
                return $this->error('报名结束时间必须小于活动结束时间');
            }
        }

        if(!empty($input['company_id'])){

            $company_id = $input['company_id'];

            unset($input['company_id']);

        }
        //判断是否是全选公司
        if($input['is_public']==0&&!empty($company_id)){

            $atv_model  = new AtvCompany();

            $company_id = $atv_model->changeData($company_id);

            $this->companyAdd($company_id,$input['id']);
        }

        $validate = new ActivityValidate();

        $this->_input['content_text'] = !empty($this->_input['content_text'])?$this->_input['content_text']:'';

        $check = $validate->scene('update')->check($this->_input);
        if ($check == false)
        {
            return $this->error($validate->getError());
        }


        $model = new ActivityModel();
        $rst = $model->updateByfilter(['id' => $activity_id], $input);

        $arcitity_item_ids = explode(',', $this->_input['items'] ?? '');
        if ($arcitity_item_ids)
        {
            $items_model = new \app\activity\model\ActivityItem();
            $acticity_items_data = $items_model->getAllByIds($arcitity_item_ids);

            $time = time();
            $saveData = [];
            foreach ($acticity_items_data as $data) {
                $saveData[] = [
                    'create_time' => $time,
                    'update_time' => $time,
                    'activity_id' => $activity_id,
                    'uniacid' => $this->_uniacid,
                    'title' => $data['title']
                ];
            }

            $activityItemsInActivityModel = new ActivityItemsInActivity();

            $activityItemsInActivityModel->destoryByactivityId($activity_id);

            $activityItemsInActivityModel->saveAll($saveData);
        }

        return $this->success($rst);
    }

    public function getOne()
    {
        $validate = new ActivityValidate();
        $check = $validate->scene('get')->check($this->_param ?? []);
        if ($check == false)
        {
            return $this->error($validate->getError());
        }

        $activity_id   = $this->_param['id'];
        $model = new ActivityModel();
        $data = $model->getOne(['id' => $activity_id]);

        $data['sign_start_time'] = $data['sign_start_time'] == 0 ? $data['start_time'] : $data['sign_start_time'] ;
        $data['sign_end_time'] = $data['sign_end_time'] == 0 ? $data['end_time'] : $data['sign_end_time'] ;


        $data = transImagesOne($data, ['cover']);
        $data = transImages($data, ['carousel', 'detail_images'], ';');

        $data['detail_images'] = $data['detail_images'] == '' ? [] : $data['detail_images'];
        $data['carousel'] = $data['carousel'] == '' ? [] : $data['carousel'];

        $data['content_text'] = !empty($data['content_text'])?$data['content_text']:$data['text_desc'];

        $items_in_activity = $data['activityItems'] ?? [];

        $titles = array_column($items_in_activity, 'title');

        $m_item = new ActivityItem();

        $items = $m_item->field('id, title')->where([['title', 'in', $titles], ['status', '=', 1], ['uniacid', '=', $this->_uniacid]])->select()->toArray();
        foreach ($items as $item) {
            $data['items'][] = (int)$item['id'];
        }

        $atv_model  = new AtvCompany();

        if($data['is_public']==1){

            $data['company_id'] = $atv_model->getCompanyIds([
                'uniacid' => $this->_uniacid,
                'status'  => 1,
            ]);
        }else{
            $data['company_id'] = $atv_model->getId([
                'a.uniacid' => $this->_uniacid,
                'a.atv_id'  => $activity_id,
                'b.status'  => 1,
            ]);
        }

        return $this->success($data);
    }

    public function changeStatus()
    {
        $validate = new ActivityValidate();
        $check = $validate->scene('updateStatus')->check($this->_input);
        if ($check == false)
        {
            return $this->error($validate->getError());
        }

        $activity_id   = $this->_param['id'];
        $input = $this->_input;
        $model = new ActivityModel();
        $rst = $model->updateByfilter(['id' => $activity_id], ['status' => $input['status']]);
        return $this->success($rst);
    }
}